
// cartConfirm.js
var app = getApp()
Page({
    data: {
        integral_checked : true,
        isGroupbuying: false,
        tid: 0,
        use_integral : 0
    },
    
    //messageChange
    messageChange : function(e){
        var value = e.detail.value

        this.setData({
            message : value
        })
    },
    calcPrice : function(){
        var thiz = this
        var pay_goods = thiz.data.pay_goods
        const {isGroupbuying, groupbuyingPrice} = this.data;

        var totalPrice = 0

        // console.log(this.data.serial_number)

        pay_goods.forEach(function (element, index) {
            totalPrice += element.amount * (isGroupbuying ? groupbuyingPrice : element.price)
        })

        thiz.setData({
            totalPrice: totalPrice
        })
    },
    goodsAddClick : function(e){
        var thiz = this
        var id = e.currentTarget.dataset.id
        var cartStorage = thiz.data.cartGoodsArray
        var pay_goods = thiz.data.pay_goods

        pay_goods.forEach(function(element, index){
            if (element.id == id){
                element.amount++
            }
        })

        cartStorage.forEach(function (element, index) {
            if (element.goods_id == id) {
                element.amount++
            }
        })

        thiz.setData({
            cartGoodsArray: cartStorage,
            pay_goodsArray: pay_goods
        })

        thiz.calcPrice()

    },
    goodsReduceClick : function(e){
        var thiz = this
        var id = e.currentTarget.dataset.id
        var cartStorage = thiz.data.cartGoodsArray
        var pay_goods = thiz.data.pay_goods


        pay_goods.forEach(function (element, index) {
            if (element.id == id) {
                if (element.amount > 1){
                    element.amount--
                }
            }
        })

        cartStorage.forEach(function (element, index) {
            if (element.goods_id == id) {
                if (element.amount > 1) {
                    element.amount--
                }
            }
        })

        thiz.setData({
            cartGoodsArray: cartStorage,
            pay_goodsArray: pay_goods
        })

        thiz.calcPrice()
    },
    
    //支付方法
    pay: function (order_data){
        var thiz = this
        var domain = app.globalData.domain
        var user_id = app.globalData.inv_i
        var payUrl = app.globalData.PageInterface
      
        wx.request({
            url: domain + payUrl,
            method: 'POST',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            data: {
              format_type: 'json',
              api_cate: 'Order',
              model: "MINI",
              api: 8008,              
              user_id:user_id,
              order_sn: order_data.order_id
            },
            success: function (r) {
                wx.requestPayment({
                    timeStamp: r.data.timeStamp,
                    nonceStr: r.data.nonceStr,
                    package: r.data.package,
                    signType: r.data.signType,
                    paySign: r.data.paySign,
                    success: function (e) {
                        wx.showToast({
                            title: '支付成功'
                        })
                        
                    },
                    fail: function (e) {
                        wx.showToast({
                            title: '支付失败'
                        })
                    },
                    complete: function (re) {

                        wx.redirectTo({
                            url: '../order_detail/order_detail?order_id=' + order_data.order_id,
                        })
                    }
                })
            }
        })
    },
    //提交订单
    postOrder : function(){
        var thiz = this

        if (!thiz.data.addrData){
            wx.showToast({
                title: '请填写地址',
            })
            return
        }

        var address_id = this.data.addrData.address_id

        var domain = app.globalData.domain
        var postOrderUrl = app.globalData.PageInterface
        var user_id = app.globalData.inv_i
        var payUrl = app.globalData.PageInterface
        var postOrder = domain + postOrderUrl;

        var array = []

        this.data.cartGoodsArray.forEach(function(element, index){
            var order_info = {
                goods_id : element.goods_id,
                goods_spec_id: element.goods_spec_id,
                amount : element.amount
            }
            array.push(order_info)
        })
        // console.log('address_id:',address_id);return false;
        wx.request({
          url: postOrder,
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          data: {
            format_type: 'json',            
            api_cate: 'Order',
            model: "MINI",
            api: 8005,
            c_id: thiz.data.cartGoodsArray[0].c_id,
            user_id: user_id,
            goods_id: thiz.data.cartGoodsArray[0].goods_id,
            option_id: thiz.data.cartGoodsArray[0].goods_spec_id,
            goods_num: thiz.data.cartGoodsArray[0].amount,
            address_id: address_id,
            // order_info: JSON.stringify(array),
            order_message: thiz.data.message, 
          },
          success: function(res){
            if(thiz.data.type == 'cart'){

              var no_pay_goods = wx.getStorageSync('no_pay_goods')

              //处理清空购物车问题
              wx.setStorageSync('cartStorage', no_pay_goods)
              wx.removeStorageSync('pay_goods')
            }
            if(res.data.status == 1){
                var order_data = res.data.data

                //如果选择了优惠券玛
                if (thiz.data.serial_number){
                    wx.request({
                        url: domain + couponInterface,
                        method: 'POST',
                        header: { 'content-type': 'application/x-www-form-urlencoded' },
                        data: {
                            format_type: 'json',
                            api_cate: 'Coupon',
                            api: 6009,
                            sn: thiz.data.serial_number,
                            order_sn: order_data.order_sn,
                            kui_key: kui_key
                        },
                        success: function (res) {

                            if (res.data.status == 0) {
                                wx.showToast({
                                    title: res.data.message,
                                })
                                return
                            }

                            if (res.data.status == 1) {
                                if (thiz.data.use_integral == 0) {
                                    thiz.pay(order_data)
                                } else {
                                    thiz.integral(order_data)
                                }
                            }
                        }
                    })
                }else{
                    if (thiz.data.use_integral == 0){
                        thiz.pay(order_data)
                    }else{
                        thiz.integral(order_data)
                    }

                }
            }else{
                wx.request({
                    url: '提交失败，请退出重试',
                })
            }
        }
      })



    },

    /**
     * 选择地址
     */
    raddrManageClick : function(){
        var thiz = this
        var str = JSON.stringify(this.data.postGoods);
        var str2 = JSON.stringify(this.data.pay_goods);
        wx.redirectTo({

          url: '../addrManage/addrManage?type=2' + '&postGoods=' + str + '&pay_goods=' + str2 + '&totalPrice=' + thiz.data.totalPrice,
        })
    },
    //地址管理点击
    addrManageClick : function(){
        var thiz = this
        var str = JSON.stringify(this.data.postGoods);
        var str2 = JSON.stringify(this.data.pay_goods);

        wx.redirectTo({
            url: '../addrSelect/addrSelect?pay_goods=' + str2 + '&postGoods=' + str + '&totalPrice=' + thiz.data.totalPrice,
        })

        // wx.redirectTo({
        //   url: '../addrSelect/addrSelect?pay_goods=' + str2 + '&postGoods='+str+'&totalPrice=' + thiz.data.totalPrice,
        // })
    },
    onShow : function(){
      console.log(this.data.postGoods)
        var thiz = this
        var domain = app.globalData.domain
        var addrListUrl = app.globalData.PageInterface
        var cid = app.globalData.cid
        var user_id = app.globalData.inv_i

        var addrList = domain + addrListUrl;

        if(thiz.data.coupon){
          if (thiz.data.coupon.type_id == 1) {
            var  totalPrcie = 0;
            if (JSON.parse(thiz.data.totalPrice) - JSON.parse(thiz.data.coupon.remain_value) > 0){
              totalPrcie = JSON.parse(thiz.data.totalPrice) - JSON.parse(thiz.data.coupon.remain_value)
            }
            //现金券
            thiz.setData({
              discount: thiz.data.coupon.remain_value,
              autalPrice: totalPrcie
            })
          }

          if (thiz.data.coupon.type_id == 3) {
            var discount = JSON.parse(thiz.data.totalPrice) * JSON.parse(thiz.data.coupon.coupon_value)
            
            var totalPrice = JSON.parse(thiz.data.totalPrice) - discount.toFixed(2)
            thiz.setData({
              discount: discount.toFixed(2),
              autalPrice: totalPrice.toFixed(2),
            })
          }
        }
        //地址选择默认
        if(thiz.data.address_id == ""){
            wx.request({
              url: addrList,
              method: 'POST',
              header: { 'content-type': 'application/x-www-form-urlencoded' },
              data: {
                  api_cate:'Personal',
                  user_id: user_id,
                  model:"MINI",
                  api:7002,
                  moren:1
              },
              success: function (res) {
                  if(res.data.status==1){
                    thiz.setData({
                      addrData: res.data.data[0],
                      hiddenLoading: true
                    })
                  }else{
                      thiz.setData({
                          hiddenLoading: true
                      })
                  }
              }
            })
        }


        var cartStorage = thiz.data.postGoods
        var pay_goods = thiz.data.pay_goods
        var array = []
        cartStorage.forEach(function(element, index){
            var cartGoods = {
                goods_id: element.goods_detail.goods_id,
                name: element.goods_detail.goods_name,
                spec: element.active_goods_options.option_title,
                goods_spec_id: element.active_goods_options.goods_option_id,
                price: element.active_goods_options.price,
                amount: element.amount,
                img_url: domain + '/' + element.goods_detail.default_img,
                c_id: element.goods_detail.c_id
            }
            array.push(cartGoods)
        })

        
        thiz.setData({
            cartGoodsArray: array,
            pay_goodsArray:pay_goods
        })

        thiz.calcPrice()
    },
    goToUseCoupon: function () {
        var thiz = this

        if (thiz.data.couponList.length != 0){
            wx.navigateTo({
                url: '../useCoupon/useCoupon',
            })
        }

    },
    loadFee : function(){

      
      var thiz = this

      var domain = app.globalData.domain
      var commonInterface = app.globalData.commonInterface
      var cid = app.globalData.cid
      var kui_key = app.globalData.kui_key

      var str = '';
      for(var i  in thiz.data.pay_goods){
        // console.log(i)
        str += thiz.data.pay_goods[i].id + ','
      }

      wx.request({
        url: domain + commonInterface,
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          format_type: 'json',
          api_cate: 'Shippingfee',
          api:'edit',
          kui_key: kui_key,
          c_id : cid,
          goods_ids : str
        },
        success: function (res) {
          var fee = 0
          if(res.data.status == 1){
            if(res.data.data){
              fee = res.data.data.fee
            }
          }

          thiz.setData({
            fee : fee,
            totalPrice : thiz.data.totalPrice + JSON.parse(fee),
            discount :0,
            autalPrice: thiz.data.totalPrice + JSON.parse(fee)
          })
        }
      })
    },


    onLoad: function (options) {


        var thiz = this;

        var background_color = app.globalData.background_color



        if(options && options.address_id){
            thiz.setData({
                address_id : options.address_id
            })
        }else{
            thiz.setData({
                address_id: ""
            })
        }

       

        //获取系统信息
        wx.getSystemInfo({
            success: function (res) {
                thiz.setData({
                    type : options.type ? options.type : '',
                    hiddenLoading : false,
                    groupbuyingPrice : options.totalPrice,
                    postGoods: JSON.parse(options.postGoods),
                    pay_goods: JSON.parse(options.pay_goods),
                    windowHeight: res.windowHeight,
                    windowWidth: res.windowWidth
                });
            }
        })


        thiz.loadFee()

    }
})